﻿using EM.FrameWork.Paging;
using EM.OA.BLL;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EM.OA.Portal.Controllers
{
    public class AttachmentController : BaseAuthController
    {
        #region Attach
        public ActionResult Index(string refID, string type)
        {
            if (!string.IsNullOrEmpty(refID))
            {
                ViewData["refID"] = refID;
            }
            else
            {
                ViewData["refID"] = Guid.Empty.ToString();
            }
            if (!string.IsNullOrEmpty(type))
            {
                ViewData["type"] = type;
            }
            else
            {
                ViewData["type"] = "";
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            HttpPostedFileBase file = Request.Files[0];
            if (!string.IsNullOrEmpty(file.FileName))
            {
                string path = Server.MapPath("/UploadFiles");
                string refID = GetParam("refID");
                string fileName = refID + file.FileName;
                Guid objectID = Guid.Empty;
                Guid.TryParse(refID, out objectID);
                AttachmentBLL bll = new AttachmentBLL();
                EMOA_Attachment entity = new EMOA_Attachment
                {
                    AttachmentID = Guid.NewGuid(),
                    ObjectID = objectID,
                    ShowName = file.FileName,
                    FolderUrl = path,
                    FileName = fileName,
                    DownTimes = 0,
                    CreateBy = CurrentUser.UserID,
                    CreateTime = DateTime.Now
                };
                if (bll.Add(entity))
                {
                    string serverPath = Path.Combine(entity.FolderUrl, entity.FileName);
                    file.SaveAs(serverPath);
                    return Redirect("/Attachment?refID=" + entity.ObjectID.ToString());
                }
                else
                {
                    return Content("增加失败");
                }

            }

            return base.Redirect("~/attachment?refid=" + Request.Form["refKEY"].ToString());
        }

        /// <summary>
        /// 下载选中的文件（可多选）
        /// </summary>
        /// <param name="fileName">文件名集，每个文件名之间以分号隔开</param>
        /// <returns></returns>
        public ActionResult DownloadFile(string id)
        {
            AttachmentBLL bll = new AttachmentBLL();
            EMOA_Attachment entity = bll.GetEntity(Guid.Parse(id));
            if (entity != null)
            {
                string fileName = entity.FileName;
                string fileType = Path.GetExtension(entity.FileName);
                string serverPath = Path.Combine(Server.MapPath("/UploadFiles"), entity.FileName);
                FileInfo fi = new FileInfo(serverPath);
                FileStream fileStream = new FileStream(serverPath, FileMode.Open);
                int length = (int)fileStream.Length;
                byte[] buffer = new byte[length];
                fileStream.Read(buffer, 0, length);
                fileStream.Close();
                byte[] fileContent = buffer;

                if (Request.Browser.Browser.Equals("IE", StringComparison.OrdinalIgnoreCase))
                {
                    fileName = Url.Encode(fileName);
                }

                return File(fileContent, fileType, fileName);
            }
            return null;
        }

        #endregion

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public JsonResult GetList(string page, string rows)
        {
            Guid bizID = Guid.Empty;
            string refID = GetUrlParam("refID");

            List<object> result = new List<object>();
            AttachmentBLL bll = new AttachmentBLL();
            List<EMOA_Attachment> list = bll.GetList(
                p =>
                {
                    if (refID.IsNotEmpty() && Guid.TryParse(refID, out bizID) && refID != Guid.Empty.ToString())
                        return p.ObjectID == bizID;
                    else
                        return false;
                });
            list.ForEach(p =>
            {
                result.Add(new AttachmentModels().ToModel(p));
            });

            return ToJson(result, list.Count);
        }


        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string id)
        {
            try
            {
                AttachmentBLL bll = new AttachmentBLL();
                EMOA_Attachment entity = bll.GetEntity(Guid.Parse(id));
                if (bll.Delete(Guid.Parse(id)))
                {
                    string path = Path.Combine(entity.FolderUrl, entity.FileName);
                    System.IO.File.Delete(path);
                    return Content("OK");
                }
                else
                    return Content("删除失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }
    }
}